//
//  M4SecondInfoViewController2.swift
//  M4
//
//  Created by YuChuang on 2025/1/21.
//

import UIKit
import AddressBookUI

class M4SecondInfoViewController2: M4BaseViewController {
    
    lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .white
        scroll.contentSize.width = M4ScreenWidth
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        return scroll
    }()
    
    lazy var tipImageView: M4InfosTopKycTipImageView = {
        let view = UINib(nibName: "M4InfosTopKycTipImageView", bundle: nil).instantiate(withOwner: self).last as! M4InfosTopKycTipImageView
        view.M4TipimageView.image = UIImage(named: "img_schedule2")
        
        view.setStyledCreditText(amountText: "$ 20,000",typestr: 2)
        return view
    }()
    
    lazy var bottomView: M4InfosBottomView = {
        let view = M4InfosBottomView()
        view.m4BottomButtonBlock = { button in
            self.view.endEditing(true)
            //提交信息
//            let vc = M4ThirdInfoViewController()
//            self.navigationController?.pushViewController(vc, animated: true)
//            button.M4EventUnavailable = false
            self.M4SubmitSecondInfoNet()
        }
        return view
    }()
    
    private var m4contactTFViews: [M4ContactInputView2] = []
    
    private var m4chooseTag: Int = 0
    
    private var m4enterTime: Int = 0
    
    private var m4RelationKeys: [String] = ["Mjpb", "LIy", "gKsf", "tjfs", "gkjd"]
    
    private var m4PhoneKeys: [String] = ["YlWc", "XSGXEL", "bkKd", "Bjhcsef", "eJcb"]
    
    private var m4NameKeys: [String] = ["Plu", "MPhPc", "ogsf", "NJdGfc", "oVxxs"]

    override func viewDidLoad() {
        super.viewDidLoad()

        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Información de contacto", M4NavTitleColor: COLOR_333333)
        m4updateUI()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        view.endEditing(true)
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        M4InfosPageBack()
        sender.M4EventUnavailable = false
    }
    
    private func m4updateUI() {
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
        }
        scrollView.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
        for i in 0..<M4CreditStatusManager.m4CreditShare.m4isContactCount {
            let view = UINib(nibName: "M4ContactInputView2", bundle: nil).instantiate(withOwner: self).last as! M4ContactInputView2
            m4contactTFViews.append(view)
            view.M4ContactItemMobileTF.tag = i
            view.M4ContactItemNameTF.tag = i
            view.M4ContactItemTitle.text = i == 0 ? "Padre/Madre" : "Amigo"
            view.M4ContactItemNameTF.delegate = self
            view.M4ContactItemMobileTF.delegate = self
            scrollView.addSubview(view)
            view.snp.makeConstraints { make in
                make.top.equalTo(tipImageView.snp.bottom).offset(110 * i)
                make.left.right.equalToSuperview()
                make.height.equalTo(110)
                make.width.equalTo(M4ScreenWidth)
            }
            if i == M4CreditStatusManager.m4CreditShare.m4isContactCount - 1 {
                scrollView.addSubview(bottomView)
                bottomView.snp.makeConstraints { make in
                    make.top.equalTo(view.snp.bottom).offset(20)
                    make.left.right.equalToSuperview()
                    make.bottom.equalToSuperview().offset(-20)
                    make.width.equalTo(M4ScreenWidth)
                }
            }
        }
    }
    
    private func M4SubmitSecondInfoNet() {
        for i in 0..<2 {
            if m4contactTFViews[i].M4ContactItemNameTF.text?.count == 0 {
                self.view.makeToast("Por favor, elija el nombre del contacto", position: .center)
                self.bottomView.m4submitButton.M4EventUnavailable = false
                return
            }
            else if m4contactTFViews[i].M4ContactItemMobileTF.text?.count == 0 {
                self.view.makeToast("Por favor, elija el número de teléfono de contacto", position: .center)
                self.bottomView.m4submitButton.M4EventUnavailable = false
                return
            }
        }
        let m4endTime = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        var param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 3, "HyHzRWokXbo": m4endTime]
        for k in 0..<m4contactTFViews.count {
            param1[m4RelationKeys[k]] = k == 0 ? 1 : 5
            param1[m4PhoneKeys[k]] = m4contactTFViews[k].M4ContactItemMobileTF.text
            param1[m4NameKeys[k]] = m4contactTFViews[k].M4ContactItemNameTF.text
        }
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.bottomView.m4submitButton.M4EventUnavailable = false
            if model.code == 1 {
                let vc = M4ThirdInfoViewController()
                self.navigationController?.pushViewController(vc, animated: true)
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
}

extension M4SecondInfoViewController2: UINavigationControllerDelegate, ABPeoplePickerNavigationControllerDelegate {
    
    @objc private func M4SecondItemTap(sender: UIButton) {
        m4chooseTag = sender.tag
        let con = ABPeoplePickerNavigationController()
        con.delegate = self
        con.peoplePickerDelegate = self
        con.modalPresentationStyle = .fullScreen
        self.present(con, animated: true)
        sender.M4EventUnavailable = false
    }
    
    func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
        
        let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty)?.takeRetainedValue() as? String ?? ""
        let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty)?.takeRetainedValue() as? String ?? ""
        let fullName = firstName + " " + lastName
        var phone: String = ""
        
        if let phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty)?.takeRetainedValue() as? ABMultiValue {
            for index in 0..<ABMultiValueGetCount(phoneNumbers) {
                let phoneNumber = ABMultiValueCopyValueAtIndex(phoneNumbers, index)?.takeRetainedValue() as? String
                print("mobole: \(phoneNumber ?? "")")
                phone = phoneNumber ?? ""
                break
            }
        }
        
        if !M4VerifyMobileFormat(mobile: phone, isSelect: true) {
           return
        }
        
        m4contactTFViews[m4chooseTag].M4ContactItemNameTF.text = fullName
        m4contactTFViews[m4chooseTag].M4ContactItemMobileTF.text = phone
    }
    
    //改为手动输入
//    func peoplePickerNavigationControllerDidCancel(_ peoplePicker: ABPeoplePickerNavigationController) {
//        m4contactTFViews.forEach { view in
//            view.M4ContactItemButton.isHidden = true
//            view.M4ContactItemNameTF.isUserInteractionEnabled = true
//            view.M4ContactItemMobileTF.isUserInteractionEnabled = true
//            view.M4ContactItemMobileTF.delegate = self
//        }
//    }
    
    private func M4VerifyMobileFormat(mobile: String, isSelect: Bool) -> Bool {
        //M4CreditStatusManager.m4CreditShare.m4phonePattern
        for k in 0..<m4contactTFViews.count {
            if isSelect {
                if mobile == m4contactTFViews[k].M4ContactItemMobileTF.text {
                    self.view.makeToast("El número de teléfono de contacto no debe ser el mismo", position: .center)
                    return false
                }
            }
            else {
                if k != m4chooseTag {
                    if mobile == m4contactTFViews[k].M4ContactItemMobileTF.text {
                        self.view.makeToast("El número de teléfono de contacto no debe ser el mismo", position: .center)
                        return false
                    }
                }
            }
            
        }
        
        var mobileString = mobile.replacingOccurrences(of: " ", with: "")
        mobileString = mobileString.replacingOccurrences(of: "(", with: "")
        mobileString = mobileString.replacingOccurrences(of: ")", with: "")
        mobileString = mobileString.replacingOccurrences(of: "-", with: "")
        mobileString = mobileString.replacingOccurrences(of: "+", with: "")
        if mobileString.prefix(3) == "+52" {
            mobileString.removeFirst(3)
        }
        else if mobileString.prefix(2) == "52"{
            mobileString.removeFirst(2)
        }
        
//        if mobileString.count != 10 {
//            self.view.makeToast("El número de teléfono móvil del contacto está mal formado", position: .center)
//            return false
//        }
//
        if mobileString == M4UserDataManager.m4UserShare.M4UserMobile {
            self.view.makeToast("El número de teléfono móvil del contacto no puede registrarse para ti", position: .center)
            return false
        }
        
        if mobile.count > 16 || !M4IsPatternCharacters(in: mobile, pattern: M4CreditStatusManager.m4CreditShare.m4phonePattern) {
            self.view.makeToast("El número de teléfono móvil del contacto está mal formado", position: .center)
            return false
        }
        
        return true
    }
    
    func M4IsPatternCharacters(in string: String, pattern: String) -> Bool {
        let expression = try? NSRegularExpression(pattern: pattern, options: [])
        let numberOfCharacters = expression?.numberOfMatches(in: string, options: [], range: NSMakeRange(0, string.count))

        return numberOfCharacters == 0 ? false : true
      }
    
}

extension M4SecondInfoViewController2: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        m4chooseTag = textField.tag
        if textField == m4contactTFViews[m4chooseTag].M4ContactItemNameTF {
            guard let textString = textField.text else {return true}
            let length = textString.count + string.count - range.length
            if length > 30 {
                textField.endEditing(true)
                return false
            }
        }
        if textField == m4contactTFViews[m4chooseTag].M4ContactItemMobileTF {
            guard let textString = textField.text else {return true}
            let length = textString.count + string.count - range.length
            if textString.prefix(2) == "52" && length <= 12 {
                return true
            }
            else if length <= 10 {
                return true
            }
            textField.endEditing(true)
            return false
        }
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        m4chooseTag = textField.tag
        if textField == m4contactTFViews[m4chooseTag].M4ContactItemMobileTF {
            if !M4VerifyMobileFormat(mobile: textField.text ?? "", isSelect: false) {
                m4contactTFViews[m4chooseTag].M4ContactItemMobileTF.text = ""
               return
            }
        }
    }
    
}

